<?php

namespace app\common\model;

use think\Exception;
use think\Log;
use think\Model;
use traits\model\SoftDelete;

class Artificer extends Model
{
    use SoftDelete;
    protected $name = 'artificer';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'aptitude_images_url',
        'category_text',
    ];

    public function getAptitudeImagesUrlAttr($value,$data)
    {
        return isset($data['aptitude_images']) && $data['aptitude_images'] ? cdnurl($data['aptitude_images'],true) : '';
    }

    public function getCategoryTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['category_ids']) ? $data['category_ids'] :'');
        $list = Category::where('id','in',$value)->column('name');
        return $list ? implode('、',$list) : '';
    }

    public function user()
    {
        return $this->belongsTo(User::class)->setEagerlyType(0);
    }

    /**
     * 设置错误信息
     * @param $msg
     */
    public function setError($msg)
    {
        $this->error = $msg;
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * 商品列表
     * @param array $where
     * @param int $limit            数量
     * @param int $page             页码
     * @param bool $pageStatus       是否分页   false：不分页   true  分页
     * @param array $extend       补充参数，如 lng经度、lat 纬度用于计算距离distance
     * @return void
     */
    public function list($where= [], $limit = 10, $page = null, $pageStatus = false,$extend = []){
        try {
            $limit = $limit ? $limit : 10;
            $page = $page ? $page : 1;
            $tempWhere = [
                'state' => ['=','20'],    //  上架
            ];
            $field = 'id,name,category_ids,self_intro,user_id';
            $where = array_merge($tempWhere,$where);
            $sql = self::where($where)
                ->order('id desc')
                ->field($field);
            if($pageStatus){
                $list = $sql->paginate($limit,true,['page'=>$page])->each(function ($item){
                    $item->avatar = $item->user->avatar;
                    $item->categoryArr = isset($item->category_text) ? explode('、',$item->category_text) : [];
                    unset($item->user);
                    return $item;
                });
            }else{
                $list = $sql->select();
                if($list ){
                    foreach ($list as $k=>&$v){
                        $v['categoryArr'] = isset($v['category_text']) ? explode('、',$v['category_text']) : [];
                        $v['avatar'] = $v['user']['avatar'];
                        unset($v['user']);
                    }
                }
            }
            return $list;
        }catch (Exception $e){
            Log::write('商品列表，SQL 语句：'.(new self())->getLastSql(),'log',true);
            $this->setError($e->getMessage());
            Log::write('商品列表，错误信息：'.$e->getMessage(),'error',true);
            return false;
        }
    }

    /**
     * 技工详情
     * @param $id
     * @return void
     */
    public function details($id){
        try {
            $artificer = self::get($id);
            if(empty($artificer)){
                $this->setError(__('No results were found'));
                return false;
            }
            $data = [
                'id' => $artificer->id,
                'categoryArr' => isset($artificer->category_text) ? explode('、',$artificer->category_text) : [],
                'user_id' => $artificer->user_id,
                'name' => $artificer->name,
                'store_location' => $artificer->store_location,
                'lng' => $artificer->lng,
                'lat' => $artificer->lat,
                'address' => $artificer->address,
                'self_intro' => $artificer->self_intro,
            ];
            return $data;
        } catch (Exception $e) {
            $this->setError($e->getMessage());
            return false;
        }
    }

    /**
     * 查找技工（援救分配技工，就近查找）
     * @param $lng   经度
     * @param $lat   纬度
     * @param $arr   排除已分配未接单的技工，数组或者空字符串
     * @return int   技工ID
     */
    public function seek($lng, $lat, $arr = [])
    {
        try {
            //  审核通过，可接单的技工
            $where = ['state'=>['=','20'],'take_switch'=>['=',1]];
            if($arr){
                $where['id'] = ['not in',$arr];
            }
            $row = self::where($where)->field('id,'."round(st_distance_sphere(point($lng, $lat),point(lng, lat))/1000,2) as distance")->order('distance asc')->find();
            if(empty($row)){
                throw new Exception('暂无技工可接单，请稍后再试！');
            }
            $id = $row->id;
        }catch (Exception $e){
            $this->setError($e->getMessage());
            return  false;
        }
        return $id;
    }

}